package org.cy.websocket.stomp.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created in 2021-05-13 18:10
 *
 * @author cao.yong
 */
@RestController
public class StompServerController {

    private static final Logger LOG = LoggerFactory.getLogger(StompServerController.class);
    private final SimpMessagingTemplate sender;

    public StompServerController(SimpMessagingTemplate sender) {
        this.sender = sender;
    }

    @MessageMapping("/broadcast/msg")
    public void broadcastMsg(Message<String> message) {
        LOG.info("Recv Topic Message: {}", message.getPayload());
        this.sender.convertAndSend("/topic/broadcast", "Auto Topic Success!");
    }

    @MessageMapping("/single/msg")
    public void singleMsg(Message<String> message) {
        LOG.info("Recv Single Message: {}", message.getPayload());
        SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class);
        assert accessor != null;
        String id = accessor.getFirstNativeHeader("deviceName");
        assert id != null;
        this.sender.convertAndSendToUser(id, "/msg", "Auto Single Success!");
    }
}
